package com.aliyun.tiangong.base;

import com.aliyun.tiangong.support.RestResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Map;
import java.util.Objects;

/**
 * @author xinghen
 * @ClassName: BaseController
 * @Package: com.aliyun.tiangong.base
 * @Description 通用Controller
 * @create 2018-04-20 11:36
 */
public class BaseController {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 处理返回结果
     *
     * @param message
     * @param result
     * @param <T>
     * @return
     */
    protected <T> RestResult<T> handleResult(String message, T result) {
        if (isSuccess(result)) {
            return RestResult.ok(result);
        } else {
            return RestResult.error(message);
        }
    }

    /**
     * 处理返回结果
     *
     * @param result
     * @param <T>
     * @return
     */
    protected <T> RestResult<T> handleResult(T result) {
        if (isSuccess(result)) {
            return RestResult.ok(result);
        } else {
            return RestResult.error();
        }
    }

    /**
     * 校验是否成功返回
     *
     * @param result
     * @param <T>
     * @return
     */
    private <T> boolean isSuccess(T result) {
        boolean isSuccess;
        if (result instanceof Integer) {
            isSuccess = (Integer) result > 0;
        } else if (result instanceof Boolean) {
            isSuccess = (Boolean) result;
        } else if (result instanceof String) {
            isSuccess = StringUtils.isNotBlank((String) result);
        } else if (result instanceof Collection) {
            isSuccess = CollectionUtils.isNotEmpty((Collection) result);
        } else if (result instanceof Map) {
            isSuccess = MapUtils.isNotEmpty((Map) result);
        } else {
            isSuccess = Objects.nonNull(result);
        }
        return isSuccess;
    }

}
